import { defineStore } from 'pinia';
import { fetchLogin } from '@/service';
import { setLocal, removeLocal } from '~/src/utils';
import { useRouterPush } from '@/utils';
import { ElNotification } from 'element-plus';
import { useRouteStore } from '../router';
interface AuthStoreProps {
  loginLoading: boolean;
  token: string;
  userInfo?: AuthApi.LoginResult['data'],
  rootRedirect:string;
}

export const useAuth = defineStore('useAuth', {
  state: ():AuthStoreProps => {
    return {
      loginLoading: false,
      token: '',
      userInfo: undefined,
      rootRedirect: import.meta.env.VITE_APP_ROOTREDIRECT
    };
  },

  actions: {
    //对登录返回结果处理
    async handleLoginResult(res: AuthApi.LoginResult) {
      const { userInfo, token } = res;
      this.token = token;
      this.userInfo = userInfo;
      // 添加token到浏览器缓存
      setLocal('token', token);
      setLocal('userName',  userInfo?.userName);
      setLocal('pageAuth',  userInfo?.auth);
      const isReady =  await useRouteStore().initRouter();
      if(isReady){
        //跳转定义的根路径
        const  { toLoginRedirect }  = useRouterPush(false);
        toLoginRedirect();
        this.loginLoading = false;
        ElNotification({
          message: `欢迎回来 ${userInfo?.userName}`,
          type: 'success',
          duration: 3000
        });
      }else {
        console.error('出问题了～');
      }
    },


    async login(userInfo: AuthApi.UserInfoRequest)  {
      this.loginLoading = true;
      const { data } = await fetchLogin(userInfo);
      if(data && data.token){
        setTimeout(() => {
          this.handleLoginResult(data);
        }, 700);
      }else {
        this.loginLoading= false;
      }
    },
    /**清楚用户信息缓存 */
    cleanUserCache(){
      removeLocal('token');
    }
  }

});
